package com.example.guiguiapplicatio.fragment.followup;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.icu.util.Calendar;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.guiguiapplicatio.api.Entity.FollowUp;
import com.example.guiguiapplicatio.api.Interface.Api;
import com.example.guiguiapplicatio.LocalSaveActivity;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.Record;
import com.example.guiguiapplicatio.databinding.FragmentHypertensionBinding;
import com.example.guiguiapplicatio.databindingBean.FollowupHypertension;
import com.example.guiguiapplicatio.databindingBean.followup.FollowupWith;
import com.example.guiguiapplicatio.databindingBean.followup.ListFollowupWith;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.example.guiguiapplicatio.utils.EditIsCanUseBtnUtils;
import com.example.guiguiapplicatio.utils.IsNumericUtils;
import com.example.guiguiapplicatio.utils.JsonUtil;
import com.example.guiguiapplicatio.utils.PreferencesUtil;
import com.example.guiguiapplicatio.utils.ToastUtil;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class HypertensionFragment extends Fragment {

    private FragmentHypertensionBinding binding;
    private Record record;
    private FollowUp followUp;
    private FollowupWith followupWith;
    private ListFollowupWith listFollowupWith;
    private FollowupHypertension hypertension;
    private FollowupHypertension tempHypertension;
    private int doctorId;
    private Retrofit retrofit;
    private Api api;
    private List<CheckBox> checkBoxList=new ArrayList<>();
    private boolean IS_FOLLOWUP_TO_REPORT_THIS = false;
    private boolean IS_EXIST_FOLLOWUP_TO_THIS = false;
    private boolean IS_WITHOUT_NET=false;
    NavController navController;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

        // retrofit2初始化
        OkHttpClient client = new OkHttpClient.Builder().
//                 readTimeout(30, TimeUnit.SECONDS).
//                writeTimeout(30, TimeUnit.SECONDS).
        connectTimeout(6, TimeUnit.SECONDS).build();//用于设置请求超时等限制时间

        retrofit = new Retrofit.Builder()
                .baseUrl(getString(R.string.api))
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        api = retrofit.create(Api.class);
        // retrofit2初始化

        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentHypertensionBinding.inflate(inflater, container, false);
        navController = Navigation.findNavController(container);
        // Inflate the layout for this fragment

        initDate();
        setBack();
        setSelectWay(binding.selectWayBtn, binding.selectWayLayout, IS_EXIST_FOLLOWUP_TO_THIS);
        inClick();
        setCheckBoxs();
        setDatePicker();
        setRadioGroup();

        return binding.getRoot();
    }
    private void setEditWall() {
        binding.editWall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getContext()!=null){
                    ToastUtil.showToast(getContext(), "非该随访医师不可编辑！");
                }
            }
        });

        if (!followUp.getDoctorId().equals(doctorId)){
            binding.editWall.setVisibility(View.VISIBLE);
        }
    }
    private void initCheckBoxs() {
        if (hypertension.getSymptom().length()>0){
            String[] strs = hypertension.getSymptom().split(";");
            for (int i = 0; i < strs.length; i++) {

                for (int j = 0; j < checkBoxList.size(); j++) {
                    if (strs[i].equals(checkBoxList.get(j).getText())){
                        checkBoxList.get(j).setChecked(true);
                        break;
                    }
                    if (j==checkBoxList.size()-1){
                        checkBoxList.get(j).setChecked(true);
                        binding.checkbox10Situation.setText(strs[i]);
                    }
                }

            }
        }
    }

    private void setLocalSave() {
        ActivityResultLauncher launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if(result.getResultCode() == Activity.RESULT_OK){

                    Log.d("data_return", result.getData().getStringExtra("data_return"));
                    Gson gson=new Gson();
                    String dataReturn=result.getData().getStringExtra("data_return");

                    String json=dataReturn.substring(1,dataReturn.length()-1).replaceAll("\\\\","");

                    hypertension=gson.fromJson(json, FollowupHypertension.class);
                    configurationData(false);

                }
            }
        });

        Intent intent = new Intent(getActivity(), LocalSaveActivity.class);
        binding.saveLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);
                Gson gson=new Gson();
                intent.putExtra("dataType",hypertension.getClass().getName());
                intent.putExtra("data",gson.toJson(hypertension));
                intent.putExtra("IS_SAVE",true);
                launcher.launch(intent);//启动intent跳转
            }
        });

        binding.loadLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);
                intent.putExtra("dataType",hypertension.getClass().getName());
                intent.putExtra("IS_SAVE",false);
                launcher.launch(intent);//启动intent跳转
            }
        });

    }

    private void configurationData(boolean isReload){

        //拷贝
        Gson gson = new Gson();
        tempHypertension = gson.fromJson(gson.toJson(hypertension), FollowupHypertension.class);
        //拷贝

        followupWith = new FollowupWith();
        followupWith.setFollow(followUp);
        followupWith.setObject(hypertension);
        binding.setHyp(hypertension);

        initRadioGroup();
        initCheckBoxs();
        if (!isReload){
            setEditWall();
        }


        initSpinner();
    }

    private void initRadioGroup() {
        if (hypertension.getMedicationCardFill()!=null){

            if (hypertension.getMedicationCardFill().equals("1")){
                binding.radioMedicine1.setChecked(true);
            }else if (hypertension.getMedicationCardFill().equals("0")){
                binding.radioMedicine0.setChecked(true);
            }

        }

        if (hypertension.getPrecautions()!=null){

            if (hypertension.getPrecautions().equals("1")){
                binding.radioPrecautions1.setChecked(true);
            }else if (hypertension.getPrecautions().equals("0")){
                binding.radioPrecautions0.setChecked(true);
            }

        }

    }

    private void setRadioGroup() {
        binding.radioMedicine.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
               if (checkedId==binding.radioMedicine1.getId()){
                   hypertension.setMedicationCardFill(String.valueOf(1));
               }else {
                   hypertension.setMedicationCardFill(String.valueOf(0));
               }
            }
        });

        binding.radioPrecautions.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId==binding.radioPrecautions1.getId()){
                    hypertension.setPrecautions(String.valueOf(1));
                }else {
                    hypertension.setPrecautions(String.valueOf(0));
                }
            }
        });

    }

    private void setDatePicker() {
        binding.nextDate.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onClick(View v) {
                DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        month = month + 1;
                        String str = year + "-" + month + "-" + dayOfMonth ;//把日期变成字符串格式显示出来
                        binding.nextDate.setText(str);//文本框显示的内容设置成经过逻辑处理后的日期
                    }
                };
                Calendar calendar = Calendar.getInstance();
                new DatePickerDialog(getContext(), 5, onDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });
    }

    private void setCheckBoxsInit() {
        String s="";
        for (int i = 0; i < checkBoxList.size(); i++) {
            if (checkBoxList.get(0).isChecked()){
                s=s+checkBoxList.get(0).getText();
                for (int j = 1; j < checkBoxList.size(); j++) {
                    checkBoxList.get(j).setChecked(false);
                }
                break;
            }


            if (checkBoxList.get(i).isChecked()){
                if (i==checkBoxList.size()-1){
                    s=s+binding.checkbox10Situation.getText();

                }else {
                    s=s+checkBoxList.get(i).getText()+";";
                }
            }

        }
        hypertension.setSymptom(s);
    }

    private void setCheckBoxs() {
        checkBoxList.clear();
        checkBoxList.add(binding.checkbox1);
        checkBoxList.add(binding.checkbox2);
        checkBoxList.add(binding.checkbox3);
        checkBoxList.add(binding.checkbox4);
        checkBoxList.add(binding.checkbox5);
        checkBoxList.add(binding.checkbox6);
        checkBoxList.add(binding.checkbox7);
        checkBoxList.add(binding.checkbox8);
        checkBoxList.add(binding.checkbox9);
        checkBoxList.add(binding.checkbox10);

        for (int i = 0; i < checkBoxList.size(); i++) {
            checkBoxList.get(i).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    setCheckBoxsInit();
                }
            });
        }
    }


    private void inClick() {

        binding.updata.setOnClickListener(new View.OnClickListener() {//更新
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);

                if (hypertension.equals(tempHypertension)) {
                    Toast.makeText(getContext(), "无修改", Toast.LENGTH_LONG).show();
                } else {
                    boolean b = checkStringsIsNum();
                    if (b) {
                        setCheckBoxsInit();
                        Call<ResponseBody<Object>> objectCall = api.updateFollowUp(followupWith);
                        dialogToApi("确认更新？", objectCall);
                    }
                }
            }
        });


        binding.upload.setOnClickListener(new View.OnClickListener() {//上传网络
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);

                Boolean haveEmpty = EditIsCanUseBtnUtils.getInstance()
                        .addEdittext(binding.diastolicBloodPressure)
                        .addEdittext(binding.systolicBloodPressure)
                        .addEdittext(binding.dailyDrinkAmount)
                        .addEdittext(binding.dailySmokingAmount)
                        .build();

                if (haveEmpty == true) {//检测限制的的输入框是有空

                    Toast.makeText(getContext(), "请继续完善信息", Toast.LENGTH_LONG).show();

                } else {

                    boolean b = checkStringsIsNum();
                    if (b) {
                        followUp.setState(1);
                        setCheckBoxsInit();
                        Call<ResponseBody<Object>> objectCall = api.upLoadFollowUp(followupWith);
                        dialogToApi("确认上传正式随访？", objectCall);
                    }
                }
            }
        });

        binding.save.setOnClickListener(new View.OnClickListener() {//上穿草稿
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);

                boolean b = checkStringsIsNum();
                if (b) {
                    setCheckBoxsInit();
                    followUp.setState(0);
                    Call<ResponseBody<Object>> objectCall = api.upLoadFollowUp(followupWith);
                    dialogToApi("确认上传随访草稿？", objectCall);
                }


            }
        });

        binding.updataToFormal.setOnClickListener(new View.OnClickListener() {//转为正式
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);
                Boolean haveEmpty = EditIsCanUseBtnUtils.getInstance()
                        .addEdittext(binding.diastolicBloodPressure)
                        .addEdittext(binding.systolicBloodPressure)
                        .addEdittext(binding.dailyDrinkAmount)
                        .addEdittext(binding.dailySmokingAmount)
                        .build();

                if (haveEmpty == true) {//检测限制的的输入框是有空

                    Toast.makeText(getContext(), "请继续完善信息", Toast.LENGTH_LONG).show();

                } else {

                    boolean b = checkStringsIsNum();
                    if (b) {
                        followUp.setState(1);
                        setCheckBoxsInit();
                        Call<ResponseBody<Object>> objectCall = api.updateFollowUp(followupWith);
                        dialogToApi("确认转为正式随访？", objectCall);
                    }
                }
            }

        });

        binding.delete.setOnClickListener(new View.OnClickListener() {//删除草稿
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);
                Call<ResponseBody<Object>> objectCall = api.deleteFollowUp(followupWith);
                dialogToApi("确认删除随访草稿？", objectCall);

            }
        });


        setLocalSave();

    }

    private boolean checkStringsIsNum() {

        return IsNumericUtils.getInstance().addContext(getContext())
                .addString(hypertension.getSystolicBloodPressure())
                .addString(hypertension.getDiastolicBloodPressure())
                .addString(hypertension.getHeartRate())
                .addString(hypertension.getHeight())
                .addString(hypertension.getWeight())
                .addString(hypertension.getBmi())
                .addString(hypertension.getNextWeight())
                .addString(hypertension.getNextBmi())
                .addString(hypertension.getDailySmokingAmount())
                .addString(hypertension.getNextDailyDrinkAmount())
                .addString(hypertension.getDailyDrinkAmount())
                .addString(hypertension.getNextDailyDrinkAmount())
                .addString(hypertension.getMedicationCardFill())
                .isAllNumeric();
    }

    private void setBack() {
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
    }

    private void initDate() {

        if (getArguments().getBoolean("IS_EXIST_FOLLOWUP_TO_THIS")) {
            IS_EXIST_FOLLOWUP_TO_THIS = getArguments().getBoolean("IS_EXIST_FOLLOWUP_TO_THIS");
        }

        if (getArguments().getBoolean("IS_FOLLOWUP_TO_REPORT_THIS")) {
            IS_FOLLOWUP_TO_REPORT_THIS = getArguments().getBoolean("IS_FOLLOWUP_TO_REPORT_THIS");
        }

        IS_WITHOUT_NET=getArguments().getBoolean("IS_WITHOUT_NET");
        doctorId= PreferencesUtil.getInt(getContext(),"doctor_id");

        if (IS_EXIST_FOLLOWUP_TO_THIS) {
            listFollowupWith = (ListFollowupWith) getArguments().getSerializable("ListFollowupWith");
            followUp = listFollowupWith.getFollowUp();
            Call<ResponseBody<FollowupWith>> call = api.getOneFollowupWith(followUp.getId());
            binding.name.setText(listFollowupWith.getPatientName());
            call.clone().enqueue(new Callback<ResponseBody<FollowupWith>>() {
                @Override
                public void onResponse(Call<ResponseBody<FollowupWith>> call, Response<ResponseBody<FollowupWith>> response) {
                    ResponseBody<FollowupWith> responseBody = response.body();
                    if (!responseBody.equals(null)) {
                        if (responseBody.getMsg().equals("无数据")) {
                            Toast.makeText(getContext(), "错误!无数据", Toast.LENGTH_LONG).show();
                            getActivity().onBackPressed();
                        } else {
                            String json = JsonUtil.toJson(responseBody.getData().getObject());
                            hypertension = JsonUtil.fromJson(json, FollowupHypertension.class);

                            configurationData(true);
                        }

                    } else {
                        Toast.makeText(getContext(), "数据获取错误", Toast.LENGTH_LONG).show();
                        getActivity().onBackPressed();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody<FollowupWith>> call, Throwable t) {
                    if (getContext() != null) {
                        Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                        getActivity().onBackPressed();
                    }
                }
            });

        } else {
            followupWith = new FollowupWith();
            followUp = new FollowUp();
            hypertension = new FollowupHypertension();
            binding.setHyp(hypertension);

            record = (Record) getArguments().getSerializable("Record");
            followUp.setFollowUpType("高血压");
            followUp.setIdCard(record.getIdcard());
            followUp.setDoctorId(doctorId);

            binding.name.setText(record.getName());
            followupWith.setFollow(followUp);
            followupWith.setObject(hypertension);
            setSpinner();
        }


    }

    private void initSpinner(){
        ArrayAdapter<CharSequence> adapter = null;
        adapter=ArrayAdapter.createFromResource(getContext(), R.array.followup_type, android.R.layout.simple_spinner_item);
        binding.followupTypeSpinner.setAdapter(adapter);
        Log.e("setSpinner", "setSpinner: "+hypertension.getFollowUpMode().equals("线下随访")+hypertension.getFollowUpMode()+hypertension.getFollowUpMode().equals("线上随访"));
        if (hypertension.getFollowUpMode().equals("线下随访")){
            binding.followupTypeSpinner.setSelection(0);
        }else if (hypertension.getFollowUpMode().equals("线上随访")){
            binding.followupTypeSpinner.setSelection(1);
        }
        binding.followupTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view;
                if (hypertension!=null){
                    hypertension.setFollowUpMode((String) textView.getText());
                }else {
                    Log.e("onItemSelected", "onItemSelected: hypertension"+hypertension);
                }
                Log.e("onItemSelected", "onItemSelected: "+textView.getText());

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void setSpinner() {
        ArrayAdapter<CharSequence> adapter = null;
        adapter=ArrayAdapter.createFromResource(getContext(), R.array.followup_type, android.R.layout.simple_spinner_item);
        binding.followupTypeSpinner.setAdapter(adapter);

        binding.followupTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position==0){
                    hypertension.setFollowUpMode("线下随访");
                }else if (position==1){
                    hypertension.setFollowUpMode("线上随访");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        binding.followupTypeSpinner.setSelection(0);


    }

    private void setSelectWay(Button selectWayBtn, LinearLayout selectWayLayout, boolean IS_EXIST) {
        selectWayLayout.setVisibility(View.GONE);
        selectWayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectWayLayout.getVisibility() == View.VISIBLE) {
                    selectWayLayout.setVisibility(View.GONE);
                } else {
                    selectWayLayout.setVisibility(View.VISIBLE);
                }
            }
        });

        if (IS_EXIST){
            if (followUp.getState()==0){//草稿
                binding.saveLocal.setVisibility(View.GONE);
                binding.save.setVisibility(View.GONE);
                binding.upload.setVisibility(View.GONE);
            }else if (followUp.getState()==1){ //正式
                binding.updataToFormal.setVisibility(View.GONE);
                binding.save.setVisibility(View.GONE);
                binding.delete.setVisibility(View.GONE);
                binding.upload.setVisibility(View.GONE);
                binding.saveLocal.setVisibility(View.GONE);
                binding.loadLocal.setVisibility(View.GONE);
            }

        }else {
            binding.updataToFormal.setVisibility(View.GONE);
            binding.updata.setVisibility(View.GONE);
            binding.delete.setVisibility(View.GONE);
            if (IS_WITHOUT_NET){//无网络
                binding.save.setVisibility(View.GONE);
                binding.upload.setVisibility(View.GONE);
            }
        }


    }

    private void dialogToApi(String title, Call<ResponseBody<Object>> objectCall) {
        AlertDialog aldg;
        AlertDialog.Builder adBd = new AlertDialog.Builder(getContext());
        adBd.setTitle(title);
        adBd.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.e("objectCall", " objectCall: " + objectCall);
                objectCall.clone().enqueue(new Callback<ResponseBody<Object>>() {

                    @Override
                    public void onResponse(Call<ResponseBody<Object>> call, Response<ResponseBody<Object>> response) {
                        if (response.body() != null) {
                            Toast.makeText(getContext(), response.body().getMsg(), Toast.LENGTH_SHORT).show();
                            if (IS_FOLLOWUP_TO_REPORT_THIS) {
                                getActivity().onBackPressed();
                            } else {
                                navController.navigate(R.id.action_hypertensionFragment_to_navigation_follow_up);
                            }
                            ///代码复用注意修改
                        } else {
                            Log.e("onResponse", "onResponse:   为空！！");
                            if (getContext() != null) {
                                Toast.makeText(getContext(), "onResponse:   为空！！", Toast.LENGTH_LONG).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<Object>> call, Throwable t) {
                        Log.e("onFailure", "onFailure: ！" + t);
                        if (getContext() != null) {
                            Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });
        adBd.setNegativeButton("取消", null);
        aldg = adBd.create();
        aldg.show();

    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }
}